/*
 * File      : bb_mem.c
 * This file is part of Black Bird Simulation Platform
 * Copyright 2013-2020 BB(Black Bird) Development Team.  
 * All rights reserved.
 *
 * Change Logs:
 * Date           Author       Notes
 * 2014-03-24    Holt         First Version
 */
#include "bb_mem.h"

const bb_except_t EXCEPT_mem_failed={"Memory allocation failed"};
/*
 * FUNC		:	allocate a block memory
 *
 * PARAM1	:	the numbers of byte
 * PARAM2	:	the source file where this function inserted 
 * PARAM3	:	the line of file where this function inserted 
 *
 * RETURN 	:	address of the alocated block
 *
 */
void *bb_mem_alloc(bb_base_long nbytes,const char*file,const bb_base line)
{
	void*p;
	
	bb_assert(nbytes>0);
	p = malloc(nbytes);
	if( p == NULL)
	{
		if(file == NULL)
			BB_RAISE(EXCEPT_mem_failed);
		else
			bb_except_raise(EXCEPT_mem_failed, file, line);
	}
	else
	{
		return p;
	}
}

/*
 * FUNC		:	allocate counts of block memory and initilize 0
 *
 * PARAM1	:	the count of blocks
 * PARAM2	:	the numbers of byte in a block
 * PARAM3	:	the source file where this function inserted 
 * PARAM4	:	the line of file where this function inserted 
 *
 * RETURN 	:	address of the alocated block
 *
 */
void *bb_mem_calloc(bb_base_long count,bb_base_long nbytes,const char*file,const bb_base line)
{
	void*p;
	
	bb_assert(count>0);
	bb_assert(nbytes>0);
	p = calloc(count,nbytes);
	if( p == NULL)
	{
		if(file == NULL)
			BB_RAISE(EXCEPT_mem_failed);
		else
			bb_except_raise(EXCEPT_mem_failed, file, line);
	}
	else
	{
		return p;
	}
}

/*
 * FUNC		:	free memory
 *
 * PARAM1	:	the address of memory
 * PARAM2	:	the source file where this function inserted 
 * PARAM3	:	the line of file where this function inserted 
 *
 * RETURN 	:	none
 *
 */
void bb_mem_free(void*p,const char *file,const bb_base line)
{
	if(p)
		free(p);
}

/*
 * FUNC		:	resize memory
 *
 * PARAM1	:	the address of memory
 * PARAM2	:	the byte numbers in the block
 * PARAM3	:	the source file where this function inserted 
 * PARAM4	:	the line of file where this function inserted 
 *
 * RETURN 	:	none
 *
 */
void *bb_mem_resize(void*p,bb_base_long nbytes,const char*file,const bb_base line)
{
	bb_assert(p);
	bb_assert(nbytes>0);
	p = realloc(p,nbytes);
	if( p == NULL)
	{
		if(file == NULL)
			BB_RAISE(EXCEPT_mem_failed);
		else
			bb_except_raise(EXCEPT_mem_failed, file, line);
	}
	else
	{
		return p;
	}
}

/*
 * FUNC		:	resize memory
 *
 * PARAM1	:	the address of memory
 * PARAM2	:	the byte numbers in the block
 * PARAM3	:	the source file where this function inserted 
 * PARAM4	:	the line of file where this function inserted 
 *
 * RETURN 	:	none
 *
 */